var prefs = new gadgets.Prefs();
var myService = null;
var selectedEvent = null;
var urlConcurrio = "https://calendardemosam.appspot.com/concurrio.action";

function setupMyService() {
	myService = new google.gdata.calendar.CalendarService('concurrio');
	myService.useOAuth('google');
}

function initGadget() {
	google.load('gdata', '2.x');
	google.setOnLoadCallback(setupMyService);
	google.calendar.read.subscribeToEvents(subscribeEventCallback);
	document.getElementById("main").style.display = "none";
	gadgets.window.adjustHeight();
}

function subscribeEventCallback(calendarEvent) {

	var callback = function(response){
		if (response.oauthApprovalUrl) {
			window.open(response.oauthApprovalUrl, 'Autorizar');
		} else if (response.feed) {
			var entries = response.feed.entry;
			for ( var i = 0; i < entries.length; i++) {
				var eventEntry = entries[i];
				var pos = eventEntry.getHtmlLink().href.search(calendarEvent.id);
				if (pos != -1) {
					selectedEvent = eventEntry;
					var html = "";
					var concurrio = getExtendedProperty(eventEntry.gd$extendedProperty, 'concurrio');
					if(concurrio == 'true'){
						html = "Este turno ya fue reportado. El paciente concurrió al mismo.";						
					}
					if(concurrio == 'false'){
						html = "Este turno ya fue reportado. El paciente no concurrió al mismo.";						
					}
					document.getElementById('message').innerHTML = html;
				}
			}
		} else {
			html = 'OAuth error: ' + response.oauthError + ': ' + response.oauthErrorText;
			document.getElementById('content_div').innerHTML = html;
		}
		gadgets.window.adjustHeight();
	};
		
	
	if (!calendarEvent) {
		document.getElementById("main").style.display = "none";
		gadgets.window.adjustHeight();
	} else {
		
		var feedUri = 'https://www.google.com/calendar/feeds/' + calendarEvent.calendar.email + '/private/full';
		var query = new google.gdata.calendar.CalendarEventQuery(feedUri);
		var start = calendarEvent.startTime;
		var end = calendarEvent.endTime;
		var startMin = new google.gdata.DateTime(new Date(start.year,
				start.month - 1, start.date, start.hour, start.minute,
				start.second, 0));
		var startMax = new google.gdata.DateTime(new Date(end.year, end.month - 1,
				end.date, end.hour, end.minute, end.second, 0));
		query.setMinimumStartTime(startMin);
		query.setMaximumStartTime(startMax);
		myService.getEventsFeed(query, callback, callback);
		
		var concurrioButton = document.getElementById("concurrioButton");
		var noConcurrioButton = document.getElementById("noConcurrioButton");
		concurrioButton.onclick = function() {
			marcarEvento(calendarEvent, true);
		};
		noConcurrioButton.onclick = function() {
			marcarEvento(calendarEvent, false);
		};
		document.getElementById("main").style.display = "block";
	}
}

function marcarEvento(calendarEvent, concurrio) {
	document.getElementById("content_div").style.display = "none";
	document.getElementById("loading").style.display = "block";
	document.getElementById("message").innerHTML = "";
	gadgets.window.adjustHeight();
	var numeroAfiliado = getExtendedProperty(selectedEvent.gd$extendedProperty, "map_nroAfiliado");
	if(numeroAfiliado == null){
		numeroAfiliado = prompt("Ingrese el número de afiliado",null);
		if (numeroAfiliado == null ||  name == ""){return;}
		var extendedProp = new google.gdata.ExtendedProperty();
		extendedProp.setName("map_nroAfiliado");
		extendedProp.setValue(numeroAfiliado);
		selectedEvent.gd$extendedProperty.push(extendedProp);
	}
	
	var extendedProp = new google.gdata.ExtendedProperty();
	extendedProp.setName('concurrio');
	extendedProp.setValue(concurrio);
	selectedEvent.gd$extendedProperty.push(extendedProp);
	selectedEvent.updateEntry(function(result) {}, function(error) {});
	
	var params = {};
	var postdata = {
		user : calendarEvent.creator.email,
		calendarId : calendarEvent.owner.email,
		eventId : selectedEvent.gCal$uid.value.split("@")[0],
		concurrio: concurrio,
		numeroAfiliado: numeroAfiliado
	};
	postdata = gadgets.io.encodeValues(postdata);
	params[gadgets.io.RequestParameters.CONTENT_TYPE] = gadgets.io.ContentType.JSON;
	params[gadgets.io.RequestParameters.METHOD] = gadgets.io.MethodType.POST;
	params[gadgets.io.RequestParameters.POST_DATA] = postdata;
	gadgets.io.makeRequest(	urlConcurrio, 	
							function(obj) {
								document.getElementById("content_div").style.display = "block";
								document.getElementById("loading").style.display = "none";
								gadgets.window.adjustHeight();
								if( obj.data.status == "SUCCESS"){
									if(concurrio){
										alert('Fue informada la asistencia del paciente.');																					
									}else{
										alert('Fue informada la ausencia del paciente.');
									}
								}
								
							}, 
							params);

	subscribeEventCallback(calendarEvent);
}

function getExtendedProperty(extendedProperty, name){
	for ( var i = 0; i < extendedProperty.length; i++){
		if(name == extendedProperty[i].getName()  ){
			return extendedProperty[i].getValue();
		}
	}
	return null;
}

gadgets.util.registerOnLoadHandler(initGadget);
